import { ref } from 'vue'
import { TableDataGoodInfoOrderCreate } from './types'

const goods = ref<Array<TableDataGoodInfoOrderCreate>>([
  {
    contractNo: '',
    code: '',
    goodsName: '',
    goodsSpecName: '',
    goodsBrand: '',
    qty: 0,
    img: '',
    buyTime: '',
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    town: '',
    address: '',
    isEmptyLine: true,
    type: 0,
    goodId: '',
    goodSpecId: '',
    codeId: '',
    goodsSpecCode: '',
    warrantyEndTime: '',
    warrantyStartTime: '',
    buyMarket: '',
    dl: '',
    specialBz: '',
    standard: '',
    voltage: '',
    xlh: '',
    tableType: 0,
  },
])

export default () => {
  const addGood = (good: TableDataGoodInfoOrderCreate) => {
    const goodIds = goods.value.map((item) => item.goodId)
    const goodSpecIds = goods.value.map((item) => item.goodSpecId)
    const codes = goods.value.map((item) => item.code)
    if (
      !goodIds.includes(good.goodId) ||
      !goodSpecIds.includes(good.goodSpecId) ||
      !codes.includes(good.code)
    ) {
      goods.value.push(good)
    }
  }

  const removeGood = (goodId: string, goodSpecId: string, code: string) => {
    const goodIndex = goods.value.findIndex(
      (item) => item.goodId === goodId && item.goodSpecId === goodSpecId && item.code === code,
    )
    if (goodIndex >= 0) {
      goods.value.splice(goodIndex, 1)
    }
  }

  const clearAllGoods = () => {
    goods.value = goods.value.filter((good) => good.type !== 3)
  }

  const clearAllRegisterCodes = () => {
    goods.value = goods.value.filter((good) => good.type !== 1)
  }

  const clearAllNoRegisterCodes = () => {
    goods.value = goods.value.filter((good) => good.type !== 2)
  }

  const findGood = (goodId: string, goodSpecId: string, code: string) => {
    return goods.value.find(
      (good) => good.goodId === goodId && good.goodSpecId === goodSpecId && good.code === code,
    )
  }

  return {
    goods,
    addGood,
    findGood,
    removeGood,
    clearAllGoods,
    clearAllRegisterCodes,
    clearAllNoRegisterCodes,
  }
}
